import { Button, Card, Form, Input, Select, Space, Table, message } from "antd";
import { useEffect, useState } from "react";
import React from "react";
import { SearchOutlined } from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import {
  reqGetCitiesOrDistrict,
  reqGetHosTypes,
  reqGetHospitalList,
  reqGetProvince,
  reqUpdateHospitalStatus,
} from "@/api/hospital/hospitalList";
import { DictItem, HospitalListItem, SearchParams } from "@/api/hospital/hospitalList/types";
import { Link } from "react-router-dom";
//获取 Option 组件
const { Option } = Select;

export default function HospitalList() {
  //声明省份信息的状态
  let [province, setProvince] = useState<DictItem[]>([]);
  //声明城市信息的列表
  let [cities, setCities] = useState<DictItem[]>([]);
  //声明区县的状态
  let [district, setDistrict] = useState<DictItem[]>([]);
  //定义医院类型的状态
  let [hostypes, setHostypes] = useState<DictItem[]>([]);
  //定义医院列表的状态
  let [hospitalList, setHospitalList] = useState<HospitalListItem[]>([]);
  //定义分页相关的状态
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  let [current, setCurrent] = useState<number>(1);
  //声明 loading 状态
  let [loading, setLoading] = useState<boolean>(false);
  //
  let [fresh, setFresh] = useState({});
  //将搜索条件的数据定义为状态
  let [searchParams, setSearchParams] = useState<SearchParams>({
    cityCode: undefined,
    districtCode: undefined,
    hoscode: undefined,
    hosname: undefined,
    hostype: undefined,
    provinceCode: undefined,
    status: undefined,
  });

  //声明 form 对象
  let [form] = Form.useForm();
  
  
  //表格结构
  let columns: ColumnsType<HospitalListItem> = [
    {
      title: "序号",
      render: (_, record, index) => index + 1,
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render: (value) => {
        return <img width="50" src={"data:image/png;base64," + value} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院等级",
      render: (_, record) => {
        return record.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (_, record) => {
        return record.param.fullAddress;
      },
    },
    {
      title: "状态",
      render: (_, record) => {
        return record.status ? "已上线" : "未上线"
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      render: (_, record) => {
        return (
          <Space>
            <Link to={`/syt/hospital/hospitalList/show/${record.id}`}><Button type="primary">查看</Button></Link>
            <Link to={`/syt/hospital/hospitalList/schedule/${record.hoscode}`}><Button type="primary">排班</Button></Link>
            <Button type="primary" onClick={async () => {
              //发送请求
              await reqUpdateHospitalStatus(record.id, record.status ? 0 : 1);
              //提醒
              message.success('更新成功');
              //刷新组件
              setFresh({});
            }} >{record.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
    },
  ];

  //使用 useEffect
  useEffect(() => {
    //声明函数
    let getData = async () => {
      //发送请求
      let result = await reqGetProvince();
      //更新状态
      setProvince(result);
    };
    getData();
  }, []);

  //获取医院类型数据
  useEffect(() => {
    let getData = async () => {
      //发送请求
      let hostypes = await reqGetHosTypes();
      setHostypes(hostypes);
    }
    getData();
  }, [])

  //定义 getCities 函数
  let getCities = async (provinceId: number) => {
    //修改城市元素的值
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    //调用函数获取对应城市的列表
    let cities = await reqGetCitiesOrDistrict(provinceId);
    //更新城市状态
    setCities(cities);
  };
  //定义 getDistrict 函数
  let getDistrict = async (cityCode: number) => {
    //清空区县元素的值
    form.setFieldsValue({districtCode: undefined})
    //获取区县数据
    let district = await reqGetCitiesOrDistrict(cityCode);
    //更新区县的状态
    setDistrict(district);
  };

  //useEffect 回调
  useEffect(() => {
    //声明 async 函数
    let getData = async()=>{
      //设置 loading 状态为 true
      setLoading(true);
      //获取结果
      let result = await reqGetHospitalList({
        page: current,
        limit: pageSize,
        ...searchParams
      });
      //更新状态
      setHospitalList(result.content);
      //更新数据的总数
      setTotal(result.totalElements)
      //更新loading的状态
      setLoading(false);
    }
    getData()
  }, [current, pageSize, searchParams, fresh])

  //声明 finish 回调
  let onFinish = async (values: SearchParams) => {
    //更新状态
    setSearchParams(values);
  };

  //声明 reset 函数
  let reset = () => {
    //更新搜索参数的状态
    setSearchParams({});
  };


  return (
    <Card>
      {/* 表单部分 */}
      <Form
        form={form}
        name="basic"
        onFinish={onFinish}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="provinceCode" style={{ width: 200, marginBottom: 20 }}>
          <Select placeholder="请选择省" onChange={getCities} allowClear>
            {province.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 200 }}>
          <Select placeholder="请选择市" onChange={getDistrict} allowClear>
            {cities.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 200 }}>
          <Select placeholder="请选择区" onChange={() => {}} allowClear>
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item name="hostype" style={{ width: 200 }}>
          <Select placeholder="医院类型" onChange={() => {}} allowClear>
          {hostypes.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="status" style={{ width: 200 }}>
          <Select placeholder="医院状态" onChange={() => {}} allowClear>
            <Option value="1">已上线</Option>
            <Option value="0">未上线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>

            <Button onClick={reset} htmlType="reset">清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table 
        loading={loading}
        columns={columns} 
        dataSource={hospitalList} 
        bordered  
        rowKey={'id'}
        pagination={{
          total,
          pageSize,
          current,
          onChange: (page: number, pageSize: number) => {
            //更新分页相关的状态
            setPageSize(pageSize);
            setCurrent(page);
          }
        }}
        />
    </Card>
  );
}
